'''
Created on May 25, 2012

@author: thomas_dao
'''
from web import base
from web.base import BaseHandler
from web import urls
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import blobstore
from google.appengine.api import images
import webapp2
import json
from entity.entity import Photo, Event
from web import util
from app.query import photo_async
from google.appengine.ext.ndb import model
from google.appengine.ext import ndb
from entity.entity import Album
import logging

class CreateHandler(blobstore_handlers.BlobstoreUploadHandler):
    # Add a photo into an album
    @base.user_required
    def post(self):
        # 'file' is file upload field in the form
        blob_info = self.get_uploads()[0]
        
        # Create an photo object and save to Datastore
        photo = Photo()
        album_id = self.request.params.get('album_id')
        photo.album = model.Key(Album, int(album_id))
        event_id = self.request.params.get('event_id')
        photo.event = model.Key(Event, int(event_id))
        photo.description = self.request.POST.get('photo_description')
        photo.author = util.get_current_user_key()
        photo.blob_key = blob_info.key()
        photo.url = images.get_serving_url(photo.blob_key)
        photo.put()
        
        # Redirect is a must for BlobstoreUploadHandler
        self.redirect(webapp2.uri_for('photo-read', photo_id=photo.key.id()))
    

class ReadHandler(BaseHandler):
    def get(self, photo_id):
        self.response.write(photo_id)
    

class UpdateHandler(BaseHandler):
    def post(self):
        pass
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass    

class DeleteListHandler(BaseHandler):
    @ndb.synctasklet 
    @base.user_required
    def post(self):
        photo_id_list = self.request.POST.getall('photos[]')
        photos = []
        if photo_id_list is not None and len(photo_id_list) > 0:
            for photo_id in photo_id_list:
                photo = model.Key(Photo, int(photo_id))
                photos.append(photo)
        yield ndb.delete_multi_async(photos)
        self.response.write( photos)
        
class GetUploadURLHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('%s' % blobstore.create_upload_url(webapp2.uri_for('photo-create')))


class AllPhotosHandler(BaseHandler):
    """
    This module meant for testing
    """
    @ndb.synctasklet
    def get(self):
        photos = yield photo_async.get_all()
        # Write response back
        self.response.write(json.dumps(util.ndb_to_list(photos)))            

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()